package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public boolean saveUserInfo(Map<String, String> param, String token) {
        //验证token
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        String gender = param.get("gender");
        userInfo.setSex(StringUtils.equalsIgnoreCase(gender, "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        return userInfoMapper.insert(userInfo) == 1;
    }


    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FaceEngineService faceEngineService;

    public Boolean saveUserLogo(MultipartFile file, String token) {
        //验证token
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }

        //验证是否是人像
        try {
            boolean b = faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //上传图片
        PicUploadResult result = picUploadService.upload(file);

        if (StringUtils.isEmpty(result.getName())) {
            return false;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());

        return userInfoMapper.update(userInfo, queryWrapper) == 1;
    }
}
